import cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager
import os

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']  # macOS系统自带的中文字体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题

def load_and_convert_to_gray(image_path):
    """读取并转换图像为灰度图"""
    image = cv2.imread(image_path)
    if image is None:
        raise FileNotFoundError(f"无法加载图像: {image_path}")
    return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

def apply_smoothing(image, kernel_size=5):
    """应用高斯平滑"""
    return cv2.GaussianBlur(image, (kernel_size, kernel_size), 0)

def apply_sharpening(image):
    """应用拉普拉斯锐化"""
    kernel = np.array([[-1,-1,-1],
                      [-1, 9,-1],
                      [-1,-1,-1]])
    return cv2.filter2D(image, -1, kernel)

def enhance_mri(image):
    """MRI图像增强处理"""
    # 对数变换增强对比度
    enhanced = np.log1p(image.astype(np.float64))
    enhanced = (enhanced - enhanced.min()) / (enhanced.max() - enhanced.min()) * 255
    return enhanced.astype(np.uint8)

def process_and_save_image(image_path, output_dir):
    """处理图像并保存所有结果"""
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)
    
    # 加载图像
    original_img = load_and_convert_to_gray(image_path)
    
    # 进行各种处理
    smoothed_img = apply_smoothing(original_img)
    sharpened_img = apply_sharpening(original_img)
    enhanced_img = enhance_mri(original_img)
    equalized_img = cv2.equalizeHist(original_img)
    
    # 创建一个2x3的子图布局
    plt.figure(figsize=(15, 10))
    
    # 显示原始图像
    plt.subplot(231)
    plt.imshow(original_img, cmap='gray')
    plt.title('原始图像')
    plt.axis('off')
    
    # 显示高斯平滑结果
    plt.subplot(232)
    plt.imshow(smoothed_img, cmap='gray')
    plt.title('高斯平滑处理')
    plt.axis('off')
    
    # 显示拉普拉斯锐化结果
    plt.subplot(233)
    plt.imshow(sharpened_img, cmap='gray')
    plt.title('拉普拉斯锐化处理')
    plt.axis('off')
    
    # 显示MRI增强结果
    plt.subplot(234)
    plt.imshow(enhanced_img, cmap='gray')
    plt.title('MRI图像增强')
    plt.axis('off')
    
    # 显示直方图均衡化结果
    plt.subplot(235)
    plt.imshow(equalized_img, cmap='gray')
    plt.title('直方图均衡化')
    plt.axis('off')
    
    # 调整子图之间的间距
    plt.tight_layout()
    
    # 保存处理结果
    base_name = os.path.splitext(os.path.basename(image_path))[0]
    
    # 保存综合对比图
    plt.savefig(os.path.join(output_dir, f'{base_name}_all_results.png'), 
                dpi=300, bbox_inches='tight')
    
    # 分别保存每个处理结果
    cv2.imwrite(os.path.join(output_dir, f'{base_name}_original.png'), original_img)
    cv2.imwrite(os.path.join(output_dir, f'{base_name}_smoothed.png'), smoothed_img)
    cv2.imwrite(os.path.join(output_dir, f'{base_name}_sharpened.png'), sharpened_img)
    cv2.imwrite(os.path.join(output_dir, f'{base_name}_enhanced.png'), enhanced_img)
    cv2.imwrite(os.path.join(output_dir, f'{base_name}_equalized.png'), equalized_img)
    
    # 显示图像
    plt.show()

def main():
    # 处理两张图像
    output_dir = "processed_results"
    
    # 处理第一张图像
    img_path1 = "Code_for_Huangjin/Medical-Image-Process/advanced-7/1.png"
    print("正在处理颅脑横断面图像...")
    process_and_save_image(img_path1, output_dir)
    
    # 处理第二张图像
    img_path2 = "Code_for_Huangjin/Medical-Image-Process/advanced-7/2.png"
    print("正在处理颈椎矢状面图像...")
    process_and_save_image(img_path2, output_dir)
    
    print(f"\n处理完成！所有结果已保存到 {output_dir} 目录")

if __name__ == "__main__":
    main() 